<template>
  <div class="page-more">
    <p class="first" @click="first">首页</p>
    <p class="btn prev" :class="{ disabled: inner <= 0 }" @click="onPrev"></p>
    <div class="page-num">
      <p v-for="(item, index) in all" v-show="showTab(index)" :key="item" :class="{ active: index == inner }"
        @click="onNum(index)">
        {{ item }}
      </p>
    </div>
    <p class="btn next" :class="{ disabled: inner >= all - 1 }" @click="onNext"></p>
    <p class="last" @click="last">尾页</p>
  </div>
</template>

<script>
export default {
  name: "pagination",
  props: ["all"],
  data: function () {
    return {
      curr: 0,
      inner: 0,
      loading: false,
      pageNo: 1,
      pageSize: 5,
    };
  },
  methods: {
    showTab: function (index) {
      var prev = this.pageNo - 1;
      var max = this.pageNo * this.pageSize;
      var min = prev * this.pageSize;
      return index >= min && index < max;
    },

    calPage () {
      var temp = this.inner + 1;
      var page =
        temp % this.pageSize == 0
          ? temp / this.pageSize
          : Math.floor(temp / this.pageSize) + 1;
      this.pageNo = page;
    },

    onNext: function () {
      if (this.loading) return;
      if (this.curr >= this.all - 1) return;

      this.curr++;

      var that = this;
      this.$emit("on-change", this.curr, function () {
        that.doAfter(function () {
          that.inner++;
          that.calPage();
        });
      });
    },

    onPrev: function () {
      if (this.loading) return;
      if (this.curr <= 0) return;
      this.curr--;

      var that = this;
      this.$emit("on-change", this.curr, function () {
        that.doAfter(function () {
          that.inner--;
          that.calPage();
        });
      });
    },

    onNum: function (no) {
      if (this.loading) return;
      if (this.curr == no) return;
      this.curr = parseInt(no);
      var that = this;
      this.$emit("on-change", parseInt(no), function () {
        that.doAfter(function () {
          that.inner = parseInt(no);
          that.calPage();
        });
      });
    },
    doAfter: function (after) {
      this.loading = false;
      after && after();
    },
    first () {
      if (this.loading) return;
      if (this.curr == 0) return;
      this.curr = 0;
      var that = this;
      this.$emit("on-change", parseInt(0), function () {
        that.doAfter(function () {
          that.inner = parseInt(0);
          that.calPage();
        });
      });
    },
    last () {
      if (this.loading) return;
      if (this.curr == this.all - 1) return;
      // console.log(this.all);
      this.curr = this.all - 1;
      var that = this;
      this.$emit("on-change", parseInt(this.all - 1), function () {
        that.doAfter(function () {
          that.inner = parseInt(that.all - 1);
          that.calPage();
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">

</style>
